package com.site.wisdom_construction.util;

import com.alibaba.fastjson.JSONObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.site.wisdom_construction.util.imgUtil.AliyunOSSUtil;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Author daiyifei
 * @Date 2022/6/27
 * @Description
 */
public class QrCodeUtils {

    public String drawingQrCode (Map map){
        Integer id = (Integer) map.get("id");

    try {
      // 二维码表示的内容
      String content = "http://www.pxkh888.com:8080/qrView/#/pages/index/index?id=" + id;

        //存放logo的文件夹
        //本地
        //String path = "D:/QRcode/";
        //服务器
        String path = "/root/img/";

        MultiFormatWriter
                multiFormatWriter = new MultiFormatWriter();

        Map hints = new HashMap();

        //设置UTF-8， 防止中文乱码
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        //设置二维码四周白色区域的大小
        hints.put(EncodeHintType.MARGIN, 0);
        //设置二维码的容错性
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

        //width:图片完整的宽;height:图片完整的高
        //因为要在二维码下方附上文字，所以把图片设置为长方形（高大于宽）
        int width = 400;
        int height = 460;

        //画二维码，记得调用multiFormatWriter.encode()时最后要带上hints参数，不然上面设置无效
        BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);

        String uuid = UUID.randomUUID().toString().replaceAll("-" , "");
        String tempFileName = uuid + ".jpg";
        //qrcFile用来存放生成的二维码图片（无logo，无文字）
        File qrcFile = new File(path, tempFileName);


        //开始画二维码
        MatrixToImageWriter.writeToFile(bitMatrix, "jpg" , qrcFile);

        try {
            //填写文件地址
            String Host = "codeImg";
            //上传到OSS
            String uploadUrl = AliyunOSSUtil.upload(qrcFile, Host);
            //删除缓存文件减少储存空间
            qrcFile.delete();
            return uploadUrl;
        } catch (Exception ex) {
            ex.printStackTrace();
        }


        return "null.jpg";
    } catch (Exception e) {
        e.printStackTrace();
        return "null.jpg";
    }
    }
}
